package docsync;

import java.text.ParseException;

import docsync.doclist.DocListRequest;

public class GoogleFolder implements FolderInterface {

	private DocListRequest doclist;
	private GoogleFile[] files;
	private ExtensionMapper extension_mapper;

	public GoogleFolder( ExtensionMapper extmap, DocListRequest dlr ){
		this.extension_mapper=extmap;
		this.doclist = dlr;
	}
	
	@Override
	public String toString(){
		return "Google Document";
	}
	
	@Override
	public FileInterface create(String filename) throws Exception {
		//filename is treated as title
		return new GoogleFile( this.extension_mapper, this.doclist, filename );
	}

	@Override
	public FileInterface[] getFiles() throws Exception {
		fetchfiles();
		return files;
	}

	private void fetchfiles() throws Exception, ParseException {
		if( this.files==null ){
			XmlFeed feed = doclist.getXmlFeed();
			GoogleFile [] files = new GoogleFile[feed.size()]; 
			for( int i=0; i<feed.size(); ++i ){
				files[i] = new GoogleFile( this.extension_mapper, this.doclist, feed, i );
			}
			
			this.files = files;//cache the files
		}
	}

	@Override
	public FileInterface open(String id) throws Exception {
		return findFile( id );
	}
	
	public void reset() {
		this.files=null;
	}

	@Override
	public void remove(String id) throws Exception {
		this.doclist.remove(id, findFile( id ).getEtag());
	}
	
	private GoogleFile findFile( String id ) throws Exception {
		fetchfiles();
		for( GoogleFile f: this.files ){
			if( f.getIdentifier().equals( id ) ){
				return f;
			}
		}
		throw new Exception("File does not exist: "+id);
		
	}

}
